package com.common.tree;


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;

public class NodeConvert<T extends MenuNode, R extends Tree> {
    public boolean isRootNode(T t) {
        return t.isRootNode();
    }

    private R createNode(String label, String value) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        TypeVariable<? extends Class<? extends NodeConvert>>[] typeParameters = getClass().getTypeParameters();
        TypeVariable<? extends Class<? extends NodeConvert>> typeParameter = typeParameters[1];
        Type[] bounds = typeParameter.getBounds();
        Type bound = bounds[0];
        Class<R> treeClass = (Class<R>) bound;
        Constructor<? extends Tree> constructor = treeClass.getConstructor(String.class, String.class);
        R tree = (R) constructor.newInstance(label, value);
        return tree;
    }

    public R createRootNode() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        return createNode("顶级", "-1");
    }

    public R apply(T t) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        return createNode(t.getLabel(), t.getValue());
    }


}
